package com.niiwoo.civet.trade.service.local.newRefund.common;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.account.dto.response.AccountCompanyDTO;
import com.niiwoo.civet.account.enums.CanRefundEnum;
import com.niiwoo.civet.account.service.AccountCompanyDubboService;
import com.niiwoo.civet.base.constant.OrgConstant;
import com.niiwoo.civet.base.enums.FeeTypeEnum;
import com.niiwoo.civet.trade.dao.entity.*;
import com.niiwoo.civet.trade.dao.mapper.*;
import com.niiwoo.civet.trade.dto.*;
import com.niiwoo.civet.trade.enums.BorrowerPlanRefundStatusEnum;
import com.niiwoo.civet.trade.enums.PeriodUnitEnum;
import com.niiwoo.civet.trade.enums.ProjectSubStatusEnum;
import com.niiwoo.civet.trade.enums.RepayStatusEnum;
import com.niiwoo.civet.trade.service.local.refund.CommonLocalService;
import com.niiwoo.civet.trade.utils.RepaymentUtil;
import com.niiwoo.tripod.provider.exception.BizException;
import org.apache.commons.collections.CollectionUtils;
import org.assertj.core.util.Lists;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 还款相关的公共方法 
 *
 * @author yuanguang
 * @version 1.0.0
 * 
 * update: kevin.jia 2018/05/01	
 */
@Service
public class RefundCommonService {

	private static final Logger logger = LoggerFactory.getLogger(RefundCommonService.class);

    @Autowired
    private ProjectBorrowerPlanNewMapperExt projectBorrowerPlanNewMapperExt;
    
	@Autowired
	private ProjectBorrowerPlanDetailMapperExt projectBorrowerPlanDetailMapperExt;
	
	@Autowired
	private RefundOrderMapperExt refundOrderMapperExt;
	
	@Autowired
	private RefundOrderDetailMapperExt refundOrderDetailMapper;
	
	@Autowired
	private RefundOrderDetailBizMapperExt refundOrderDetailBizMapper;
	
	@Autowired
	private ProjectBorrowerSummaryMapperExt projectBorrowerSummaryMapper;

    @Autowired
    private CommonLocalService commonLocalService;
    
    @Autowired
    private ProjectMapperExt projectMapperExt;

	@Reference(version = "1.0.0")
	private AccountCompanyDubboService accountCompanyDubboService;
	

	/**
	 * 判读标的历史是否有逾期
	 * 
	 * @param borrowerUserId
	 * @param projectId
	 * @return
	 */
	public boolean isProjectHirstoryOverdue(String borrowerUserId, Long projectId) {
		ProjectBorrowerSummary summary = projectBorrowerSummaryMapper.selectByPrimaryKey(projectId);
		
		// 当前还款摘要不为空，还款状态为逾期或坏帐
		if (null != summary && (RepayStatusEnum.OVERDUE.getCode().equals(summary.getRepayStatus()) ||
				RepayStatusEnum.BADLOANS.getCode().equals(summary.getRepayStatus()))) {
			return true;
		}
		
		// 查询历史是否逾期期数
		int overdueNums = projectBorrowerPlanNewMapperExt.countOverdueNums(borrowerUserId, projectId);
		
		return overdueNums > 0 ;
	}
	
	/**
	 * 是否可以发起还款
	 * 
	 * @param projectId
	 * @return
	 */
	public CanRefundEnum checkCanRefund(Long projectId) {
		return refundOrderMapperExt.selectInProgressOrderCount(projectId) > 0 ? CanRefundEnum.REFUNDING : CanRefundEnum.CAN_REFUND;
	}
	
	/**
	 * 获取当前可还还款的期数
	 *  
	 * @param projectBorrowerSummary
	 * @return
	 * 			返回当前待还款的最大期数，表示小于等于当前期数据还款计划都需要还清
	 */
	public Integer getCurrentToRepayPeriod(ProjectBorrowerSummary projectBorrowerSummary) {
		Date currentDate = commonLocalService.getCurrentDate();
		
		// 正常还款为摘要表的还款期数
		Integer currentPeriod = projectBorrowerSummary.getCurrentPeriod();
		if (RepayStatusEnum.NORMAL.getCode().equals(projectBorrowerSummary.getRepayStatus())) {
			// 如果当前期没有到可还日期，可还款期数为当前期数减1
			Date maxDate = new DateTime(currentDate).plusMonths(1).toDate();
			if (!maxDate.after(projectBorrowerSummary.getRefundDate()) && 1 != currentPeriod){
				currentPeriod--;
			}
		} else if (RepayStatusEnum.OVERDUE.getCode().equals(projectBorrowerSummary.getRepayStatus())) {
			// 逾期还款根据预计还款时间判断还款期数
			List<ProjectBorrowerPlanNew> toRepayPlanNewList = projectBorrowerPlanNewMapperExt.selectNeedRefundList(projectBorrowerSummary.getProjectId(), null);
			for (ProjectBorrowerPlanNew projectBorrowerPlanNew : toRepayPlanNewList) {
				if (RepaymentUtil.getOverdueDay(projectBorrowerPlanNew.getRefundDate(), currentDate) >= 0) {
					currentPeriod = projectBorrowerPlanNew.getPeriod();
					break;
				}
			}
		} else if (RepayStatusEnum.BADLOANS.getCode().equals(projectBorrowerSummary.getRepayStatus())) {
			// 坏帐为标的最大期数
			currentPeriod = projectBorrowerSummary.getTotalPeriod();
		}
		return currentPeriod;
	}
	
	/**
	 * 获取还款计划的逾期信息
	 * <p/>
	 * 新业务流程去除了坏帐状态、此处是否坏帐当作是逾期的一种特殊情况，因此坏帐期数同时也认为是逾期
	 * 
	 * @param projectBorrowerPlanNew
	 *            当前还款计划
	 * @param project
	 *            标的信息。用到此参数原因，现有的还款计划与还款摘要都对已结清的标无法识别是否坏帐情况
	 * @return
	 */
	public BorrowerPlanOverdueDTO getBorrowerPlanOverdueInfo(ProjectBorrowerPlanNew projectBorrowerPlanNew, Project project) {
		
		BorrowerPlanOverdueDTO borrowerPlanOverdueDTO = new BorrowerPlanOverdueDTO();
		
		Date currentDate = commonLocalService.getCurrentDate();
		Boolean isBadloan = false;
		Boolean isOverdue = false;
		Integer overdueDay = 0;
		
		// 正常结清、提前结清、正在还款预计还款日小于当前日期的为非逾期还款计划
		if (BorrowerPlanRefundStatusEnum.NORMAL_REPAYMENT.getCode().equals(projectBorrowerPlanNew.getStatus())
				|| BorrowerPlanRefundStatusEnum.OVER_DEBT_REPAYMENT.getCode().equals(projectBorrowerPlanNew.getStatus())
				|| (BorrowerPlanRefundStatusEnum.NON_REPAYMENT.getCode().equals(projectBorrowerPlanNew.getStatus())
						&& RepaymentUtil.getOverdueDay(projectBorrowerPlanNew.getRefundDate(), currentDate) <= 0)) {
			borrowerPlanOverdueDTO.setIsOverdue(isOverdue);
			borrowerPlanOverdueDTO.setIsBadloan(isBadloan);
			borrowerPlanOverdueDTO.setOverdueDay(overdueDay);
			return borrowerPlanOverdueDTO;
		}
		
		// 逾期时间
		isOverdue = true;
		
		if (BorrowerPlanRefundStatusEnum.OVERDUE_REPAYMENT.getCode().equals(projectBorrowerPlanNew.getStatus())) {
			overdueDay = RepaymentUtil.getOverdueDay(projectBorrowerPlanNew.getRefundDate(),
					projectBorrowerPlanNew.getOverCurrentDate() != null ?  projectBorrowerPlanNew.getOverCurrentDate() : projectBorrowerPlanNew.getOverDate());
		} else {
			overdueDay = RepaymentUtil.getOverdueDay(projectBorrowerPlanNew.getRefundDate(), currentDate);
		}
		
		// 是否坏帐（涉及到多期逾期，所以只能参数标的还款状态，如果逾期时间超过一个月且标的状态未坏帐还款中或者坏帐已结清才认为该还款计划期数为坏帐）

		// 当前期数还款日期下一个自然月日期
		Date refundNextMonthDate = new DateTime(projectBorrowerPlanNew.getRefundDate()).plusMonths(1).toDate();
		
		// 根据还款计划状态判断
		if (BorrowerPlanRefundStatusEnum.OVERDUE_REPAYMENT.getCode().equals(projectBorrowerPlanNew.getStatus())) {
			if ((ProjectSubStatusEnum.REPAYING_BAD.getSubStatus() == project.getSubStatus()
					|| ProjectSubStatusEnum.FINISH_BAD.getSubStatus() == project.getSubStatus())
					&& RepaymentUtil.getOverdueDay(refundNextMonthDate, projectBorrowerPlanNew.getOverDate()) > 0) {
				isBadloan = true;
			}
		} else if (BorrowerPlanRefundStatusEnum.NON_REPAYMENT.getCode().equals(projectBorrowerPlanNew.getStatus())) {
			if ((ProjectSubStatusEnum.REPAYING_BAD.getSubStatus() == project.getSubStatus())
					&& RepaymentUtil.getOverdueDay(refundNextMonthDate, currentDate) > 0) {
				isBadloan = true;
			}
		}
		borrowerPlanOverdueDTO.setOverdueDay(overdueDay);
		borrowerPlanOverdueDTO.setIsBadloan(isBadloan);
		borrowerPlanOverdueDTO.setIsOverdue(isOverdue);
		return borrowerPlanOverdueDTO;
	}
	
    /**
	 * 构建还款计划单期费用详情
	 * 
	 * @param planId
	 * @return
	 */
	public ProjectBorrowerPlanNewDetailDTO bulidProjectBorrowerPlanNewAmount(Long planId) {
		
		ProjectBorrowerPlanNewDetailDTO projectBorrowerPlanNewDetailDTO = new ProjectBorrowerPlanNewDetailDTO();
		
		// 根据还款计划ID查询明细
		List<ProjectBorrowerPlanDetail> projectBorrowerPlanDetailList = projectBorrowerPlanDetailMapperExt.selectByPlanId(planId);
		
		// 构建费用详情
		projectBorrowerPlanDetailList.forEach(projectBorrowerPlanDetail -> {
			if (FeeTypeEnum.CAPITAL.getValue().equals(projectBorrowerPlanDetail.getFeeType())) {
				projectBorrowerPlanNewDetailDTO.setCapital(projectBorrowerPlanDetail.getMoney());
				projectBorrowerPlanNewDetailDTO.setRefundedCapital(projectBorrowerPlanDetail.getRefundMoney());
			} else if (FeeTypeEnum.INTEREST.getValue().equals(projectBorrowerPlanDetail.getFeeType())) {
				projectBorrowerPlanNewDetailDTO.setInterest(projectBorrowerPlanDetail.getMoney());
				projectBorrowerPlanNewDetailDTO.setRefundedInterest(projectBorrowerPlanDetail.getRefundMoney());
			} else if (FeeTypeEnum.PENALTY.getValue().equals(projectBorrowerPlanDetail.getFeeType())) {
				projectBorrowerPlanNewDetailDTO.setPenaltyFee(projectBorrowerPlanDetail.getMoney());
				projectBorrowerPlanNewDetailDTO.setRefundedPenaltyFee(projectBorrowerPlanDetail.getRefundMoney());
			} else if (FeeTypeEnum.MANAGEMENT_FEE.getValue().equals(projectBorrowerPlanDetail.getFeeType())) {
				projectBorrowerPlanNewDetailDTO.setManagementFee(projectBorrowerPlanDetail.getMoney());
				projectBorrowerPlanNewDetailDTO.setRefundedManagementFee(projectBorrowerPlanDetail.getRefundMoney());
			} else if (FeeTypeEnum.GUARANTEE_FEE.getValue().equals(projectBorrowerPlanDetail.getFeeType())) {
				projectBorrowerPlanNewDetailDTO.setGuaranteeFee(projectBorrowerPlanDetail.getMoney());
				projectBorrowerPlanNewDetailDTO.setRefundedGuaranteeFee(projectBorrowerPlanDetail.getRefundMoney());
			}			
		});
		return projectBorrowerPlanNewDetailDTO;
	}
	
	/**
	 * 获取详细的还款计划（包含费用信息）
	 * 
	 * 此方法与projectBorrowerPlanNewMapperExt.selectByProjectIdForAmount(@Param("projectId") Long projectId)
	 * 结果一致，只是不涉及关联表查询
	 *  
	 * @param userId
	 * @param projectId
	 * @return
	 */
	public List<ProjectBorrowerPlanNewDTO> getProjectBorrowerPlanNewList(Long projectId, String userId) {
		
		List<ProjectBorrowerPlanNewDTO> projectBorrowerPlanNewDTOList = Lists.newArrayList(); 
		
		// 还款计划（按期数升序排序）
		List<ProjectBorrowerPlanNew> projectBorrowerPlanNewList = Optional.ofNullable(projectBorrowerPlanNewMapperExt.selectByProjectId(projectId))
				.orElseThrow(() -> new BizException("TRD20005"));
		
		// 循环每一期数据
		projectBorrowerPlanNewList.forEach(projectBorrowerPlanNew -> {
			ProjectBorrowerPlanNewDetailDTO projectBorrowerPlanNewDetailDTO = bulidProjectBorrowerPlanNewAmount(projectBorrowerPlanNew.getId());
			
			// 构建DTO对象
			ProjectBorrowerPlanNewDTO projectBorrowerPlanNewDTO = new ProjectBorrowerPlanNewDTO();
			projectBorrowerPlanNewDTO.setId(projectBorrowerPlanNew.getId());
			projectBorrowerPlanNewDTO.setProjectId(projectBorrowerPlanNew.getProjectId());
			projectBorrowerPlanNewDTO.setUserId(projectBorrowerPlanNew.getUserId());
			projectBorrowerPlanNewDTO.setAccountId(projectBorrowerPlanNew.getAccountId());
			projectBorrowerPlanNewDTO.setRefundDate(projectBorrowerPlanNew.getRefundDate());
			projectBorrowerPlanNewDTO.setOverDate(projectBorrowerPlanNew.getOverDate());
			projectBorrowerPlanNewDTO.setPeriod(projectBorrowerPlanNew.getPeriod());
			projectBorrowerPlanNewDTO.setPeriodType(projectBorrowerPlanNew.getPeriodType());
			projectBorrowerPlanNewDTO.setStatus(projectBorrowerPlanNew.getStatus());
			projectBorrowerPlanNewDTO.setTotalPeriod(projectBorrowerPlanNew.getTotalPeriod());
			
			projectBorrowerPlanNewDTO.setCapital(projectBorrowerPlanNewDetailDTO.getCapital() != null ? projectBorrowerPlanNewDetailDTO.getCapital() : BigDecimal.ZERO);
			projectBorrowerPlanNewDTO.setInterest(projectBorrowerPlanNewDetailDTO.getInterest() != null ? projectBorrowerPlanNewDetailDTO.getInterest() : BigDecimal.ZERO);
			projectBorrowerPlanNewDTO.setPenaltyFee(projectBorrowerPlanNewDetailDTO.getPenaltyFee() != null ? projectBorrowerPlanNewDetailDTO.getPenaltyFee() : BigDecimal.ZERO);
			projectBorrowerPlanNewDTO.setManagementFee(projectBorrowerPlanNewDetailDTO.getManagementFee() != null ? projectBorrowerPlanNewDetailDTO.getManagementFee() : BigDecimal.ZERO);
			projectBorrowerPlanNewDTO.setGuaranteeFee(projectBorrowerPlanNewDetailDTO.getGuaranteeFee() != null ? projectBorrowerPlanNewDetailDTO.getGuaranteeFee() : BigDecimal.ZERO);
			projectBorrowerPlanNewDTO.setRefundedCapital(projectBorrowerPlanNewDetailDTO.getRefundedCapital() != null ? projectBorrowerPlanNewDetailDTO.getRefundedCapital() : BigDecimal.ZERO);
			projectBorrowerPlanNewDTO.setRefundedInterest(projectBorrowerPlanNewDetailDTO.getRefundedInterest() != null ? projectBorrowerPlanNewDetailDTO.getRefundedInterest() : BigDecimal.ZERO);
			projectBorrowerPlanNewDTO.setRefundedPenaltyFee(projectBorrowerPlanNewDetailDTO.getRefundedPenaltyFee() != null ? projectBorrowerPlanNewDetailDTO.getRefundedPenaltyFee() : BigDecimal.ZERO);
			projectBorrowerPlanNewDTO.setRefundedManagementFee(projectBorrowerPlanNewDetailDTO.getRefundedManagementFee() != null ? projectBorrowerPlanNewDetailDTO.getRefundedManagementFee() : BigDecimal.ZERO);
			projectBorrowerPlanNewDTO.setRefundedGuaranteeFee(projectBorrowerPlanNewDetailDTO.getRefundedGuaranteeFee() != null ? projectBorrowerPlanNewDetailDTO.getRefundedGuaranteeFee() : BigDecimal.ZERO);
			
			projectBorrowerPlanNewDTO.setCreateTime(projectBorrowerPlanNew.getCreateTime());
			projectBorrowerPlanNewDTO.setUpdateTime(projectBorrowerPlanNew.getUpdateTime());
			
			projectBorrowerPlanNewDTOList.add(projectBorrowerPlanNewDTO);
		});
		
		return projectBorrowerPlanNewDTOList;
	}
	
	/**
	 * 查询标的费用总金额
	 * 
	 * @param projectId
	 * @param userId
	 * @return
	 */
	public ProjectRepayTotalAmountDTO getProjectTotalAmount(Long projectId, String userId) {
		ProjectRepayTotalAmountDTO projectRepayTotalAmountDTO = new ProjectRepayTotalAmountDTO(); 
		
		// 查询所有还款计划
		List<ProjectBorrowerPlanNewDTO> projectBorrowerPlanNewDTOList = getProjectBorrowerPlanNewList(projectId, userId);
		
		// 按期累加每项费用
		projectBorrowerPlanNewDTOList.forEach(projectBorrowerPlanNewDTO -> {
			projectRepayTotalAmountDTO.setTotalCapital(projectRepayTotalAmountDTO.getTotalCapital().add(projectBorrowerPlanNewDTO.getCapital()));
			projectRepayTotalAmountDTO.setTotalInterest(projectRepayTotalAmountDTO.getTotalInterest().add(projectBorrowerPlanNewDTO.getInterest()));
			projectRepayTotalAmountDTO.setTotalPenaltyFee(projectRepayTotalAmountDTO.getTotalPenaltyFee().add(projectBorrowerPlanNewDTO.getPenaltyFee()));
			projectRepayTotalAmountDTO.setTotalManagementFee(projectRepayTotalAmountDTO.getTotalManagementFee().add(projectBorrowerPlanNewDTO.getManagementFee()));
			projectRepayTotalAmountDTO.setTotalGuaranteeFee(projectRepayTotalAmountDTO.getTotalGuaranteeFee().add(projectBorrowerPlanNewDTO.getGuaranteeFee()));
		});
		
		return projectRepayTotalAmountDTO;
	}	
	
	/**
	 * 获取待还总金额（即当前标的未还总金额）
	 * 
	 * @param projectId
	 * @param userId
	 * @return
	 */
	public ProjectRepayTotalAmountDTO getProjectTotalNeedRepayAmount(Long projectId, String userId) {
		ProjectRepayTotalAmountDTO projectRepayTotalAmountDTO = new ProjectRepayTotalAmountDTO(); 
		
		// 查询所有还款计划
		List<ProjectBorrowerPlanNewDTO> projectBorrowerPlanNewDTOList = getProjectBorrowerPlanNewList(projectId, userId);
		
		// 按期累加每项费用
		projectBorrowerPlanNewDTOList.forEach(projectBorrowerPlanNewDTO -> {
			// 应还金额 = 金额 - 已还金额
			BigDecimal needRepayCapital = projectBorrowerPlanNewDTO.getCapital().subtract(projectBorrowerPlanNewDTO.getRefundedCapital());
			BigDecimal needRepayInterest = projectBorrowerPlanNewDTO.getInterest().subtract(projectBorrowerPlanNewDTO.getRefundedInterest());
			BigDecimal needRepayPenaltyFee = projectBorrowerPlanNewDTO.getPenaltyFee().subtract(projectBorrowerPlanNewDTO.getRefundedPenaltyFee());
			BigDecimal needRepayManagementFee = projectBorrowerPlanNewDTO.getManagementFee().subtract(projectBorrowerPlanNewDTO.getRefundedManagementFee());
			BigDecimal needGuaranteeFee = projectBorrowerPlanNewDTO.getGuaranteeFee().subtract(projectBorrowerPlanNewDTO.getRefundedGuaranteeFee());
			
			// 累加
			projectRepayTotalAmountDTO.setTotalCapital(projectRepayTotalAmountDTO.getTotalCapital().add(needRepayCapital));
			projectRepayTotalAmountDTO.setTotalInterest(projectRepayTotalAmountDTO.getTotalInterest().add(needRepayInterest));
			projectRepayTotalAmountDTO.setTotalPenaltyFee(projectRepayTotalAmountDTO.getTotalPenaltyFee().add(needRepayPenaltyFee));
			projectRepayTotalAmountDTO.setTotalManagementFee(projectRepayTotalAmountDTO.getTotalManagementFee().add(needRepayManagementFee));
			projectRepayTotalAmountDTO.setTotalGuaranteeFee(projectRepayTotalAmountDTO.getTotalGuaranteeFee().add(needGuaranteeFee));
		});
		
		return projectRepayTotalAmountDTO;
	}
	
	public ProjectBorrowerAmountSumDTO sumProjectBorrowerAmountByProjectId(Long projectId) {
		ProjectBorrowerAmountSumDTO projectBorrowerAmountSumDTO = new ProjectBorrowerAmountSumDTO();
		
		List<ProjectBorrowerPlanDetail> projectBorrowerPlanDetailList = projectBorrowerPlanDetailMapperExt.selectByProjectId(projectId);
		// 构建费用详情
		projectBorrowerPlanDetailList.forEach(projectBorrowerPlanDetail -> {
			if (FeeTypeEnum.CAPITAL.getValue().equals(projectBorrowerPlanDetail.getFeeType())) {
				projectBorrowerAmountSumDTO.setBorrowedAmount(projectBorrowerAmountSumDTO.getBorrowedAmount().add(projectBorrowerPlanDetail.getMoney()));
				projectBorrowerAmountSumDTO.setRefundedCapital(projectBorrowerAmountSumDTO.getRefundedCapital().add(projectBorrowerPlanDetail.getRefundMoney()));
			} else if (FeeTypeEnum.INTEREST.getValue().equals(projectBorrowerPlanDetail.getFeeType())) {
				projectBorrowerAmountSumDTO.setInterest(projectBorrowerAmountSumDTO.getInterest().add(projectBorrowerPlanDetail.getMoney()));
				projectBorrowerAmountSumDTO.setRefundedInterest(projectBorrowerAmountSumDTO.getRefundedInterest().add(projectBorrowerPlanDetail.getRefundMoney()));
			} else if (FeeTypeEnum.PENALTY.getValue().equals(projectBorrowerPlanDetail.getFeeType())) {
				projectBorrowerAmountSumDTO.setPenaltyFee(projectBorrowerAmountSumDTO.getPenaltyFee().add(projectBorrowerPlanDetail.getMoney()));
				projectBorrowerAmountSumDTO.setRefundedPenaltyFee(projectBorrowerAmountSumDTO.getRefundedPenaltyFee().add(projectBorrowerPlanDetail.getRefundMoney()));
			} else if (FeeTypeEnum.MANAGEMENT_FEE.getValue().equals(projectBorrowerPlanDetail.getFeeType())) {
				projectBorrowerAmountSumDTO.setManagementFee(projectBorrowerAmountSumDTO.getManagementFee().add(projectBorrowerPlanDetail.getMoney()));
				projectBorrowerAmountSumDTO.setRefundedManagementFee(projectBorrowerAmountSumDTO.getRefundedManagementFee().add(projectBorrowerPlanDetail.getRefundMoney()));
			} else if (FeeTypeEnum.GUARANTEE_FEE.getValue().equals(projectBorrowerPlanDetail.getFeeType())) {
				projectBorrowerAmountSumDTO.setGuaranteeFee(projectBorrowerAmountSumDTO.getGuaranteeFee().add(projectBorrowerPlanDetail.getMoney()));
				projectBorrowerAmountSumDTO.setRefundedGuaranteeFee(projectBorrowerAmountSumDTO.getRefundedGuaranteeFee().add(projectBorrowerPlanDetail.getRefundMoney()));
			}			
		});		
		return projectBorrowerAmountSumDTO;
	}
	
	/**
	 * 查询未作废还款业务详情
	 * 
	 * @param refundOrderId
	 * @return
	 */
	public List<RefundOrderDetailBiz> getNotRefundOrderDetailBizByRefundOrderId(Long refundOrderId) {
		List<RefundOrderDetailBiz> refundOrderDetailBizList = Lists.newArrayList();
		List<RefundOrderDetail> refundOrderDetailList = refundOrderDetailMapper.selectByOrderIdNotDisable(refundOrderId);
		
		List<String> detailRequestNoList = Lists.newArrayList();
		for (RefundOrderDetail refundOrderDetail : refundOrderDetailList) {
			detailRequestNoList.add(refundOrderDetail.getDetailRequestNo());
		}
		if (CollectionUtils.isNotEmpty(detailRequestNoList)) {
			refundOrderDetailBizList = refundOrderDetailBizMapper.queryRefundOrderDetailBizByDetailRequestNoList(detailRequestNoList);
		}
		return refundOrderDetailBizList;
	}	
	
	/**
	 * 本地标的子状态转换到天称对应的标的状态
	 * 
	 * @param projectSubStatus
	 * @return
	 */
	public String transformProjectStatus4TianCheng(int projectSubStatus) {
		if (ProjectSubStatusEnum.REPAYING_INIT.getSubStatus() == projectSubStatus) {
			return "5";
		} else if (ProjectSubStatusEnum.REPAYING_OVERDUE.getSubStatus() == projectSubStatus) {
			return "43";
		} else if (ProjectSubStatusEnum.REPAYING_BAD.getSubStatus() == projectSubStatus) {
			return "44";
		} else if (ProjectSubStatusEnum.FINISH_NORMAL.getSubStatus() == projectSubStatus
				|| ProjectSubStatusEnum.FINISH_ADVANCE.getSubStatus() == projectSubStatus
				|| ProjectSubStatusEnum.FINISH_OVERDUE.getSubStatus() == projectSubStatus) {
			return "6";
		} else if (ProjectSubStatusEnum.FINISH_BAD.getSubStatus() == projectSubStatus) {
			return "45";
		}
		return null;
	}

	/**
	 * 查询用户所有标的已还金额
	 * @param userId
	 * @return
	 */
	public BigDecimal selectRefundCapitalByUser(String userId){

		return projectBorrowerPlanNewMapperExt.selectRefundCapitalByUser(userId);
	}

	/**
	 * 查询用户所有逾期还款金额
	 * @param userId
	 * @return
	 */
	public BigDecimal selectOverdueAmountByUser(String userId){

		return projectBorrowerPlanNewMapperExt.selectOverdueAmountByUser(userId);
	}

	/**
	 * 查询用户所有正常还款金额
	 * @param userId
	 * @return
	 */
	public BigDecimal selectRepaymentAmountByUser(String userId){

		return projectBorrowerPlanNewMapperExt.selectRepaymentAmountByUser(userId);
	}

	/**
	 * 通过标的ID获取咨询方
	 * @param projectId
	 * @return
	 */
	public AccountCompanyDTO getConsultingByProjectId(Long projectId){
		Project project = projectMapperExt.selectByPrimaryKey(projectId);
		AccountCompanyDTO result = accountCompanyDubboService.getAccountCompanyByBusinessLicense(project.getConsultingBusinessLicense());
		if(result == null){
			logger.error("getConsultingByProjectId consulting is null. projectId:{}, consultingBusinessLicense:{}", project.getProjectId(), project.getConsultingBusinessLicense());
			throw new BizException("TRD10005", "getConsultingByProjectId consulting is null");
		}
		return result;
	}

	/**
	 * 通过标的获取咨询方
	 * @param project
	 * @return
	 */
	public AccountCompanyDTO getConsultingByProject(Project project){
		AccountCompanyDTO result = accountCompanyDubboService.getAccountCompanyByBusinessLicense(project.getConsultingBusinessLicense());
		if(result == null){
			logger.error("getConsultingByProjectId consulting is null. projectId:{}, consultingBusinessLicense:{}", project.getProjectId(), project.getConsultingBusinessLicense());
			throw new BizException("TRD10005", "getConsultingByProjectId consulting is null");
		}
		return result;
	}

	/**
	 * 是否需要按日计息
	 * @param orgId
	 * @param deadlineUnit
	 * @param refundDate
	 * @param currentDate
	 * @return
	 */
	public boolean isCalculateInterestByDay(String orgId, Byte deadlineUnit, Date refundDate, Date currentDate){
		logger.info("isCalculateInterestByDay orgId:{},deadlineUnit:{},refundDate:{},currentDate:{}", orgId, deadlineUnit, refundDate, currentDate);
		PeriodUnitEnum periodUnitEnum = PeriodUnitEnum.enumOf(deadlineUnit);
		return OrgConstant.JUNTUO_ORG_ID.equals(orgId)
				&& PeriodUnitEnum.DAY.equals(periodUnitEnum)
				&& currentDate.before(refundDate);
	}


}
